import Layout from '../components/Layout';
import React, {ReactNode, useState} from 'react';
import {CategorySection} from './money/CategorySection';
import {RecordItem, useRecords} from '../hooks/useRecords';
import {useTags} from '../hooks/useTags';
import dayjs from 'dayjs';
import styled from 'styled-components';

const Item = styled.div`
  h3{
        padding: 10px 16px;

  }
  li{
    display:flex;
    justify-content: space-between;
    background-color:#fff;
    font-size: 18px;
    line-height: 20px;
    padding: 10px 16px;
  }
  
   .note{
    margin-right: auto;
    margin-left: 16px;
    color: #ccc;
  }
`;

function Statistics() {
  const [category, setCategory] = useState<'+' | '-'>('-');
  const {records} = useRecords();
  const {getName} = useTags();
  const hash: { [key: string]: RecordItem[] } = {};
  const selectedRecords = records.filter(r => r.category === category);
  selectedRecords.forEach(r => {
    const key: string = dayjs(r.createAt).format('YYYY-MM-DD');
    const value = r;
    if (!(key in hash)) {
      hash[key] = [];
    }
    hash[key].push(value);
  });
  const array = Object.entries(hash).sort((a, b) => {
    if (a[0] === b[0]) return 0;
    if (a[0] > b[0]) return -1;
    if (a[0] < b[0]) return 1;
    return 0;
  });
  return (
    <Layout>
      <CategorySection value={category}
                       onChange={(category) => setCategory(category)}/>
      {array.map(x => <Item key={x[0]}>
        <h3>{x[0]}</h3>
        <ol>
          {x[1].map(r => {
            return <li key={r.createAt}>
              <div className="tags">
                {
                  r.tagIds
                    .map(t => <span key={t}>{getName(t)}</span>)
                    .reduce((result, item, index, array) => {
                      return result.concat(index < array.length-1 ? [item, ' '] : [item]);
                    }, [] as ReactNode[])
                }
              </div>
              {r.note && <div className="note">
                {r.note}
              </div>}
              <div className="amount">
                {r.amount}￥
              </div>
            </li>;
          })}
        </ol>
      </Item>)}
    </Layout>
  );
}

export default Statistics;
